package com.clovsoft.banner;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.DrawableWrapper;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;

import androidx.annotation.ColorInt;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class BannerTabLayout extends TabLayout {
    private StateListDrawable stateListDrawable;
    private TabLayoutMediator indicator;
    private final static int NO_Color = 0;
    private int tabSpacing = 16; // 设置默认的 tab 间距
    private int tabMinWidth;
    private int tabPaddingStart;
    private int tabPaddingEnd;
    private int layout_height;

    public BannerTabLayout(@NonNull Context context) {
        super(context);
        initView(null);
    }

    public BannerTabLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(attrs);
    }

    public BannerTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(attrs);
    }

    public void setSelectedTabIndicatorFixWidth(float width) {
        setSelectedTabIndicator(new DrawableWrapper(getTabSelectedIndicator()) {
            @Override
            public void setBounds(int left, int top, int right, int bottom) {
                int realLeft = left;
                int realRight = right;
                if ((right - left) != width) {
                    float center = left + (right - left) / 2;
                    realLeft = (int) (center - width / 2);
                    realRight = (int) (center + width / 2);
                }
                super.setBounds(realLeft, top, realRight, bottom);
            }
        });
    }

    private void initView(AttributeSet attrs) {
        try {
            if (attrs != null) {
                // 获取自定义属性的值
                TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.CustomTabLayout);
                tabMinWidth = a.getDimensionPixelSize(R.styleable.CustomTabLayout_tabMinWidth, 15);
                tabPaddingStart = a.getDimensionPixelSize(R.styleable.CustomTabLayout_tabPaddingStart, 10);
                tabPaddingEnd = a.getDimensionPixelSize(R.styleable.CustomTabLayout_tabPaddingEnd, 10);
                layout_height = a.getDimensionPixelSize(R.styleable.CustomTabLayout_layout_height, 4);
                a.recycle();
            }


        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @SuppressLint("ResourceAsColor")
    public void setDotAndSwitchColor(@NonNull Context context,
                                     @NonNull ViewPager2 viewPager2) {
        this.setDotAndSwitchColor(context, viewPager2, 0, android.R.color.darker_gray, android.R.color.holo_blue_light);
    }

    @SuppressLint("ResourceType")
    public void setDotAndSwitchColor(@NonNull Context context,
                                     @NonNull ViewPager2 viewPager2,
                                     @LayoutRes int resId,
                                     @ColorInt int dotColor,
                                     @ColorInt int switchColor) {

        new TabLayoutMediator(this, viewPager2, (tab, position) -> {
            View tabView;

            if (resId == 0) {
                tabView = LayoutInflater.from(context).inflate(R.layout.custom_tab, null, false);
            } else {
                tabView = LayoutInflater.from(context).inflate(resId, null, false);

            }
//            View view = ((LinearLayout) tabView).getChildAt(0);
            LinearLayout view = ((LinearLayout) tabView);
//            CircleView circleView = new CircleView(context);
            // 转换 dp 到 pixel
            view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {

                    // 假设你希望将宽度设为 200dp，高度设为 wrap_content
                    //params.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics());
                    //params.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics()); // 或者其他值
                    // 获取宽高
                    int width = view.getWidth();
                    int height = view.getHeight();

                    int tabh = BannerTabLayout.this.getHeight();
                    int tabw = BannerTabLayout.this.getWidth();
                    // 计算圆角半径，通常你可以选择宽度的一半或根据某种逻辑来设置
                    float cornerRadius = Math.min(width, height) / 2.0f; // 示例：设置为最小边的一半
                    if (dotColor != NO_Color && switchColor != NO_Color) {
                        StateListDrawable stateListDrawable1 = new StateListDrawable();

                        GradientDrawable gradientDrawable1 = new GradientDrawable();
                        GradientDrawable gradientDrawable2 = new GradientDrawable();
                        //圆角大小
                        gradientDrawable1.setCornerRadius(cornerRadius);

                        //背景颜色
                        gradientDrawable1.setColor(ContextCompat.getColor(context, dotColor));
                        //圆角大小
                        gradientDrawable2.setCornerRadius(cornerRadius);

                        //背景颜色
                        gradientDrawable2.setColor(ContextCompat.getColor(context, switchColor));

                        BannerTabLayout.this.setSelectedTabIndicatorColor(ContextCompat.getColor(context, switchColor));
                        //Non focused states
                        BannerTabLayout.this.setSelectedTabIndicatorHeight(height);
                        stateListDrawable1.addState(new int[]{android.R.attr.state_selected}, gradientDrawable2);
                        stateListDrawable1.addState(new int[]{}, gradientDrawable1);
                        view.setBackground(stateListDrawable1);
                        view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }
                }
            });
            tab.setCustomView(view);
        }).attach();
        applyCustomTabAttributes(tabPaddingStart, tabPaddingEnd);
    }

    private void applyCustomTabAttributes(int tabPaddingStart, int tabPaddingEnd) {
        for (int i = 0; i < getTabCount(); i++) {
            Tab tab = getTabAt(i);
            if (tab != null && tab.view != null) {
                View tabView = tab.view;
                tabView.setMinimumWidth(tabMinWidth);
                tabView.setPadding(tabPaddingStart, tabView.getPaddingTop(), tabPaddingEnd, tabView.getPaddingBottom());
            }
        }
    }

    @Override
    public void addTab(@NonNull Tab tab) {
        super.addTab(tab);
        applyCustomTabAttributes(tabPaddingStart, tabPaddingEnd);

    }

    @Override
    public void setupWithViewPager(ViewPager viewPager) {
        super.setupWithViewPager(viewPager);
        applyCustomTabAttributes(tabPaddingStart, tabPaddingEnd);
    }

    public void setTabMinWidth(int minWidth, int tabPaddingStart, int tabPaddingEnd) {
        this.tabMinWidth = minWidth;
        applyCustomTabAttributes(tabPaddingStart, tabPaddingEnd); // 更新 Tab 属性
    }

    private void adjustIndicator(int position, float positionOffset) {
        if (getTabCount() == 0) return;

        final View selectedTab = getTabAt(position).view;
        final View nextTab = position + 1 < getTabCount() ? getTabAt(position + 1).view : null;

        // Adjust the indicator to be centered
        final float left = selectedTab.getLeft() + (nextTab != null ? nextTab.getWidth() * positionOffset : 0);
        final float right = selectedTab.getRight() + (nextTab != null ? nextTab.getWidth() * positionOffset : 0);
        setIndicatorWidth(left, right);
    }

    private void setIndicatorWidth(float left, float right) {
        // Update the indicator's width and position based on the tab's width
        // You can customize this based on your design needs
    }

    public int pxToDp(int px) {
        return (int) (px / getResources().getDisplayMetrics().density);
    }
    public int dpToPx(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }
}
